<template>
    <div class="image-add-ui" :style="_styleOBJ" v-loading="loading" :element-loading-text="`已上传${Math.floor(this.progress * 10000) / 100}%`" @mouseenter="buttons = true;" @mouseleave="buttons = false;">

        <upload-ui ref="upload" class="image-ui" :disabled="disabled" :action="action" :server="server" :params="params" :accepts="accepts" :auto="autoUpload" :isCrop="isCrop" :cropInfo="cropInfo" @on-success="_success" @on-progress="_progress" @on-error="_error">
            <div class="pic-ui__layout h-100 w-100">
                <el-image :src="_preview || ''" fit="cover" class="h-100 w-100" :style="`border-radius: 5px !important;`">
                    <span slot="error"></span>
                </el-image>
                <div class="describe"></div>
            </div>
        </upload-ui>

        <span v-if="!disabled" :class="`desc ${uploadType.fileType == 'VideoType' ? 'video_color' : 'image_color'} `">{{ value ? (uploadType.fileType == 'VideoType' ? '更改视频' : '更改图片' ) : (uploadType.fileType == 'VideoType' ? '请选择视频' :  '请选择图片') }}</span>

        <transition name="el-fade-in">
            <span class="buttons corner-5" v-show="buttons" v-bind:class="{ 'is-disabled': disabled }">
                <el-button v-if="templateCover" size="mini" type="primary" class="margin-0 margin-b-10" @click="_onChoiceTemplate">模板截图</el-button>
                <el-button v-if="isLocalUplaod && !disabled" size="mini" type="success" class="margin-0" @click="_onChoiceLocal">本地文件</el-button>
                <el-button v-if="isMaterialUpload && !disabled" size="mini" type="success" class="margin-0 margin-t-10" @click="_onChioceMaterial">资源云</el-button>
            </span>
        </transition>

        <span class="icon el-icon-plus"></span>

        <!-- <ResourecCloud ref="resource-cloud-single" :types="['image']"></ResourecCloud> -->
    </div>
</template>

<script>
import UploadUI from './upload-ui';
// import MaterialDialog from './material-dialog';
import FILE from '@utils/file';
import $http from '@http';
// import ResourecCloud from '@ui/resource/select/single-dialog'
export default {
    name: 'image-add-ui',
    components: {
        [UploadUI.name]: UploadUI,
        // ResourecCloud
        // [MaterialDialog.name]: MaterialDialog,
    },
    props: {
        templateCover: { type: Boolean, default: false },
        width: { type: String, default: '100%' },
        height: { type: String, default: '100%' },
        desc: { type: String, default: '请选择图片' },
        server: { type: String, default: undefined },// 上传地址
        params: { type: Object, default() { return {} } },// 上传的参数
        accepts: { type: Array, default() { return ['.png', '.jpeg', '.jpg', '.cdr', '.bmp', '.tif', '.ico', '.gif', '.cr2'] } },// 上传文件的格式
        action: { type: String, default: undefined },
        value: { type: String, default: undefined },
        disabled: { type: Boolean, default: false },// 禁止上传
        uploadType: {
            type: Object, default() {
                return {
                    dirType: "file",			//file:文件类；mind：思维图谱类；project：项目类；dataset：数据集类；chart：图表类
                    fileType: "image"			//此类型与dirType相关
                }
            }
        },//展示的类型
        autoUpload: { type: Boolean, default: false },//媒资库选择后是否自动自动上传
        isLocalUplaod: { type: Boolean, default: true },//是否本地上传
        isMaterialUpload: { type: Boolean, default: true },//是否媒资库上传
        // 是否裁剪图片
        isCrop: { type: Boolean, default: false },
        // 裁剪信息
        cropInfo: {
            type: Object, default() {
                return {
                    autoCropWidth: 200,//裁剪框的宽度
                    autoCropHeight: 200,//裁剪框的高度
                    enlarge: 1,//裁剪出来的图片是裁剪框的倍数
                    isShowSize: true
                }
            }
        },
        fileInfo: { type: String, default: undefined },
        /**		 * 方法-> 需要返回 Promise		 */
        'on-screen-shot-async': { type: Function, default: undefined }
    },
    data() {
        return {
            progress: 0,
            type: undefined,
            coverUUID: this.value,
            loading: false,
            buttons: false
        }
    },
    watch: {
        value: {
            handler(val) {
                this.coverUUID = val;
            }, immediate: true
        },
        uploadType: {
            handler(val) {
                this.type = val;
            }, immediate: true
        }
    },

    computed: {
        _styleOBJ() {
            let width = this.width || '100%';
            let height = this.height || '100%';
            return { width, height }
        },
        _preview() {
            if (this.coverUUID) {
                return FILE.preview(this.coverUUID, 'material');
            }
            if (this.type == 'VideoType' || this.type == 'video') {
                return require('@img/file-image.png');
            }
            return require('@img/drawingBoard-white.png');
        }
    },
    methods: {
        /**
         * 选择本地文件
         */
        _onChoiceLocal() {
            this.$refs.upload.select();
        },

        /**
         * 选择媒资库文件
         */
        _onChioceMaterial() {
            // this.$refs['resource-cloud-single'].show().then(res => {
            //     let { file } = res || {}
            //     // 是否截图，是否是原图
            //     if (this.isCrop && file) {
            //         this.uploadByFileUUID(undefined, res);
            //     } else {
            //         let type = this.type;
            //         let { fileUUID, coverUUID, previewUUID } = res;
            //         let mediaRes = { fileUUID, coverUUID, previewUUID, type };
            //         this.$emit('mediaRes', mediaRes);
            //         if (this.type.fileType == 'image') {
            //             this.$emit('input', fileUUID);
            //         } else {
            //             this.$emit('input', coverUUID);
            //             this.$emit('on-change-file', fileUUID)
            //         }
            //     }
            // }).catch(() => { });
        },

        /**
         * 模板截图
         */
        _onChoiceTemplate() {
            try {
                this.onScreenShotAsync().then((file) => {
                    this.$refs.upload.add(file);
                }).catch(() => { })
            } catch (error) {
                console.error(error)
            }
        },

        /**
         * 通过fileUUID上传
         */
        uploadByFileUUID(fileUUID, res) {
            let { file, fileDetailsInfo } = res
            let { fileName } = fileDetailsInfo || {}
            const { lastModified: lastModify, size: fileSize } = file;
            const fileType = FILE.type(file);

            let fileData = { fileType, fileName, fileSize, lastModify, businessEnum: this.action, startSize: 0, file }
            let data = Object.assign({}, fileData, this.params)
            const form = new FormData();
            Object.keys(data).forEach(key => {
                form.append(key, data[key]);
            });
            console.log("开始上传");
            $http.post('file', form, { 'Content-Type': 'multipart/form-data' }).then(result => {
                this.$emit('on-success', result);

                let { fileUUID, coverUUID, previewUUID, fileType } = result || {};
                this.type = fileType
                let type = this.type;
                let mediaRes = { fileUUID, coverUUID, previewUUID, type };
                console.log(type);
                this.$emit('mediaRes', mediaRes);
                console.log('upload result', result);

                if (this.type.fileType == 'image') {

                    this.$emit('input', fileUUID);
                } else {
                    this.$emit('input', fileUUID);
                    this.$emit('on-change-file', fileUUID)
                }
            }).catch(() => {

            })
        },

        /**
         * 上传中
         */
        _progress(item) {
            this.loading = true;
            this.progress = item.progress;
            this.$emit('on-progress', item);
        },

        /**
         * 上传成功
         */
        _success(item, result) {
            this.loading = false;
            let { fileInfo: { /*fileUUID, coverUUID,*/ type } = {} } = result || {};
            this.type = type;
            if (type == 'VideoType') {
                this.$emit('input', result.coverUUID);
            } else {
                this.$emit('input', result.fileUUID);
            }
            Object.assign(result, item);
            this.$emit('on-success', result);
        },

        /**
         * 上传失败
         */
        _error() {
            this.loading = false;
            this.$emit('on-error');
        }
    }
}

</script>

<style lang="scss" scoped>
.image-add-ui {
    position: relative;
    min-width: 40px;
    min-height: 40px;
    box-sizing: border-box;
    border-radius: 4px;
    border: 2px dashed $color-border-base;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: border-color 0.3s;
    -moz-transition: border-color 0.3s;
    -webkit-transition: border-color 0.3s;
    -o-transition: border-color 0.3s;

    .buttons {
        position: absolute;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.4);
        &.is-disabled {
            background-color: rgba(0, 0, 0, 0);
            cursor: default;
        }
        .el-button {
            width: 80px;
        }
    }
    .visible {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        z-index: 100;
    }
    .image-ui {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        .pic-ui__layout {
            width: 100%;
            height: 100%;
        }
    }
    .icon {
        font-size: 16px;
        font-weight: 600;
        color: $color-border-base;
        transition: color 0.3s;
        -moz-transition: color 0.3s;
        -webkit-transition: color 0.3s;
        -o-transition: color 0.3s;
    }

    &:hover {
        border-color: $color-border-base-hover;
        .icon {
            color: $color-border-base-hover;
        }
    }

    .desc {
        position: absolute;
        right: 3px;
        bottom: 3px;
        line-height: 1;
        font-size: 12px;
    }

    .video_color {
        color: #8d8dc9e3 !important;
    }

    .image_color {
        color: $background-white;
    }

    // /deep/ .el-image__inner,
    // .el-image__placeholder,
    // .el-image__error {
    //     width: 100%;
    //     height: calc(100% - 5px);
    //     border-radius: 2px;
    // }
}
</style>